/**
 * 48. 旋转图像
 * https://leetcode-cn.com/problems/rotate-image/
 */
const { displayNestedArray } = require('../../libs/public');

// /**
//  * @param {number[][]} matrix
//  * @return {void} Do not return anything, modify matrix in-place instead.
//  */
// function rotate(matrix) {
//   const size = matrix.length;
//   for (let i = 0; i < size; i += 1) {
//     const arr = matrix[i];
//     let left = 0;
//     let right = size - 1;
//     while (left < right) {
//       const temp = arr[left];
//       arr[left] = arr[right];
//       arr[right] = temp;
//       left += 1;
//       right -= 1;
//     }
//   }
//   for (let i = 0; i < size; i += 1) {
//     for (let j = size - i - 2; j >= 0; j -= 1) {
//       const temp = matrix[i][j];
//       const targetI = size - j - 1;
//       const targetJ = size - i - 1;
//       matrix[i][j] = matrix[targetI][targetJ];
//       matrix[targetI][targetJ] = temp;
//     }
//   }
// }

/**
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */
function rotate(matrix) {
  const size = matrix.length;
  let width = size >> 1;
  const height = width;
  if ((size & 1) === 1) {
    width += 1;
  }
  for (let i = 0; i < height; i += 1) {
    for (let j = 0; j < width; j += 1) {
      const temp = matrix[i][j];
      const fromI1 = size - j - 1;
      const fromJ1 = i;
      matrix[i][j] = matrix[fromI1][fromJ1];
      const fromI2 = size - fromJ1 - 1;
      const fromJ2 = fromI1;
      matrix[fromI1][fromJ1] = matrix[fromI2][fromJ2];
      const fromI3 = size - fromJ2 - 1;
      const fromJ3 = fromI2;
      matrix[fromI2][fromJ2] = matrix[fromI3][fromJ3];
      matrix[fromI3][fromJ3] = temp;
    }
  }
}

let matrix;

matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];
rotate(matrix);
console.log(displayNestedArray(matrix) === '[[7,4,1],[8,5,2],[9,6,3]]');
matrix = [
  [5, 1, 9, 11],
  [2, 4, 8, 10],
  [13, 3, 6, 7],
  [15, 14, 12, 16],
];
rotate(matrix);
console.log(displayNestedArray(matrix) === '[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]');
